package com.study.servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hamcrest.core.Is;

/**
* @Name: FileDownloadDemo
* @Description: 文件下载
* @Author: 李超	lc_jack@foxmail.com
* @CreateDate: 2017-3-1 上午10:53:47 
* @Version: V1.0
 */
public class FileDownloadDemo extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//设置响应头信息：告诉浏览器进行文件下载
		response.setHeader("Content-Type", "application/octet-stream") ;
//		response.setHeader("Content-Disposition", "attachement;filename=1.jpg") ;
		//解决客户端下载中文文件名解析错误问题
		response.setHeader("Content-Disposition", "attachement;filename=" + URLEncoder.encode("御姐.jpg", "UTF-8")) ;
		ServletContext context = this.getServletContext() ;
//		String path = context.getRealPath("/images/1.jpg") ;
		String path = context.getRealPath("/images/御姐.jpg") ;
		InputStream in = new FileInputStream(path) ;
		OutputStream out = response.getOutputStream() ;
		byte[] buf = new byte[1024] ;
		int len = -1 ;
		while((len = in.read(buf)) != -1) {
			out.write(buf, 0, len) ;
			out.flush() ;
		}
		in.close() ;
		out.close() ;
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}

}
